<template>
  <div id="component-edit">
    <el-form
      ref="compEditFormRef"
      :model="form"
      :rules="compRules"
      label-width="130px"
    >
      <el-form-item label="组件ID" prop="componentId" style="display: none">
        <el-input v-model="form.componentId" />
      </el-form-item>
      <el-form-item label="组件名称" prop="componentName">
        <el-input v-model="form.componentName" />
      </el-form-item>
      <el-form-item label="Git地址" prop="remoteUrl">
        <el-input v-model="form.remoteUrl" />
      </el-form-item>
      <div v-if="operateType === $cons.OPERATE_TYPE_ADD">
        <el-form-item label="分支名称" prop="branch">
          <el-input v-model="form.branch" placeholder="请输入分支名，默认为master" />
        </el-form-item>
        <el-form-item label="组件TAG" prop="tag">
          <el-input v-model="form.tag" placeholder="请输入tag" />
        </el-form-item>
        <el-form-item label="组件类型" prop="compType">
          <el-select v-model="form.compType" placeholder="请选择" style="width: 100%" @change="changeCompType">
            <el-option
              v-for="item in compTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </div>
      <div v-else-if="operateType === $cons.OPERATE_TYPE_EDIT">
        <el-form-item v-if="form.selectedMode === 'branch'" label="分支名称" prop="branch">
          <el-select v-model="form.branch" filterable placeholder="请选择" style="width: 100%" @focus="fetchTagList">
            <el-option
              v-for="item in branchTagList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-else label="组件TAG" prop="tag">
          <el-select v-model="form.tag" filterable placeholder="请选择" style="width: 100%" @focus="fetchTagList">
            <el-option
              v-for="item in branchTagList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </div>
      <el-form-item label="负责人" prop="supervisor">
        <el-input v-model="form.supervisor" />
      </el-form-item>
      <el-form-item label="目录命名" prop="dirName">
        <el-input v-model="form.dirName" />
      </el-form-item>
      <el-form-item v-if="form.compType === $cons.COMP_TYPE_FRONTEND" label="是否编译" prop="isCompiled">
        <el-switch
          v-model="form.isCompiled"
          active-text="是"
          inactive-text="否"
          active-value="1"
          inactive-value="0"
        />
      </el-form-item>
      <el-form-item v-if="form.compType === $cons.COMP_TYPE_BACKEND" label="数据库名称" prop="dbName">
        <el-input v-model="form.dbName" />
      </el-form-item>
      <el-form-item label="功能描述" prop="funcDesc">
        <el-input
          v-model="form.funcDesc"
          type="textarea"
          :rows="2"
        />
      </el-form-item>
      <el-form-item label="环境信息" prop="envHost">
        <div class="tags-container">
          <!-- 标签展示区 -->
          <div class="tags-wrapper">
            <el-tag v-for="(item, index) in form.envHosts" :key="index" type="warning">{{ item }}</el-tag>
          </div>
          <!-- 固定添加按钮 -->
          <el-button class="add-btn" type="text" size="mini" @click="setCompEnv">绑定组件环境</el-button>
        </div>
      </el-form-item>
      <el-form-item v-if="form.compType !== $cons.COMP_TYPE_PYTHON" label="编译器版本" prop="compilerVersion">
        <el-select v-model="form.compilerVersion" filterable placeholder="请选择" style="width: 100%">
          <el-option
            v-for="item in complierVers"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="form.compType !== $cons.COMP_TYPE_PYTHON"
        :label="form.compType === $cons.COMP_TYPE_FRONTEND? '自定义编译命令' : '运行参数配置'"
        prop="customCmd"
      >
        <el-input v-model="form.customCmd" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="onCancel">取消</el-button>
        <el-button
          v-if="operateType === $cons.OPERATE_TYPE_EDIT"
          style="float: right;"
          type="warning"
          @click="offlineComp"
        >下线</el-button>
      </el-form-item>
    </el-form>
    <el-dialog
      v-draggable
      title="环境信息"
      :visible.sync="envVisible"
      width="50%"
      :close-on-click-modal="false"
      append-to-body
    >
      <ProjectEnvInfo
        parent-body="compBan"
        :comp-ban-env-hosts="compBanEnvHosts"
        @comp-env-cancel="compEnvCancel"
        @comp-env-submit="compEnvSubmit"
      />
    </el-dialog>
  </div>
</template>

<script>
import { constants as $const } from '@/store/constants'
import ProjectEnvInfo from '../project/ProjectEnvInfo.vue'
import {
  updateComponentInfo,
  onOfflineComps,
  getComponentEnvList
} from '@/api/component'
import { getConfigsByKey } from '@/api/config'

// git url校验
// eslint-disable-next-line no-useless-escape
const gitRegex = /^(?:https?:\/\/|git:\/\/|ssh:\/\/|git@|)(?:[a-zA-Z0-9_.-]+@)?(?:[a-zA-Z0-9.-]+)(?::[0-9]+)?[:/](?:[a-zA-Z0-9._\/-]+?)(?:\.git)?\/?$/
export default {
  name: 'ComponentEdit',
  components: { ProjectEnvInfo },
  props: {
    // 组件信息
    componentInfo: {
      type: Object,
      default: null
    },

    // 操作类型，默认为新增
    operateType: {
      type: Number,
      required: true,
      default: $const.OPERATE_TYPE_ADD
    }
  },
  data() {
    return {
      form: {
        componentId: '',
        componentName: '',
        remoteUrl: '',
        branch: '',
        tag: '',
        supervisor: '',
        dirName: '',
        funcDesc: '',
        isCompiled: '',
        dbName: '',
        isPython: '',
        envHosts: [],
        compilerVersion: '',
        customCmd: '',
        compType: 1,
        envIds: []
      },
      branchTagList: [],
      complierVers: [],
      compBanEnvHosts: [],
      envVisible: false,
      compTypes: [{
        label: '前端组件',
        value: 1
      }, {
        label: 'JAVA组件',
        value: 2
      }, {
        label: 'Python组件',
        value: 3
      }],
      compRules: {
        componentName: [{
          required: true, message: '组件名称不能为空', trigger: 'blur'
        }],
        remoteUrl: [{
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!value) {
              return callback(new Error('Git地址不能空'))
            }
            if (gitRegex.test(value)) {
              return callback()
            } else {
              return callback(new Error('请输入正确的git地址'))
            }
          }
        }],
        branch: [{
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!value && !this.form.tag) {
              return callback(new Error('分支和TAG不能同时为空'))
            } else {
              return callback()
            }
          }
        }],
        tag: [{
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!value && !this.form.branch) {
              return callback(new Error('分支和TAG不能同时为空'))
            } else {
              return callback()
            }
          }
        }],
        supervisor: [{
          required: true, message: '责任人不能为空', trigger: 'blur'
        }],
        dirName: [{
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!value && this.form.compType === this.$const.COMP_TYPE_FRONTEND) {
              return callback(new Error('前端组件必须指定目录名'))
            } else {
              return callback()
            }
          }
        }],
        envHost: [{
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (this.form.envHosts.length === 0) {
              return callback(new Error('请至少绑定一个可用环境'))
            } else {
              return callback()
            }
          }
        }]
      }
    }
  },
  computed: {
    $cons() {
      return $const
    }
  },
  emits: ['edit-cancel', 'edit-submit', 'fetch-tags', 'flush-comps'],
  mounted() {
    this.fetchConfigsByKey()
    this.initEditData()
  },
  methods: {
    initEditData() {
      if (this.operateType === 1) {
        return
      }
      this.form = { ...this.componentInfo }
      this.form['componentId'] = this.form.id
      this.branchTagList = this.componentInfo.branchTagList

      // 获取组件所在环境信息
      getComponentEnvList({ componentId: this.componentInfo.id }).then(res => {
        const list = res.data
        if (list && list.length > 0) {
          this.$set(this.form, 'envHosts', list.map(item => item.host))
        }
      }).catch(err => {
        console.error(err)
        this.$message.error('获取组件环境信息失败！！')
      })
    },

    onSubmit() {
      this.$refs['compEditFormRef'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.form.name = this.form.componentName
        // 编译环境和自定义命令不为空，则确认是否需要应用到其他项目的同一组件
        if (this.form.compilerVersion || this.form.customCmd) {
          this.$confirm('检测到当前组件自定义编译配置，是否应用到其他项目的相同组件？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.updateComponentInfo(1)
          }).catch(() => {
            this.updateComponentInfo(0)
          })
        } else {
          this.updateComponentInfo(0)
        }
      })
    },

    // 更新操作
    updateComponentInfo(isCompileConfigToAll) {
      if (this.operateType === $const.OPERATE_TYPE_ADD) {
        // 新增操作需要添加projectId
        this.form['projectId'] = this.$route.meta.projectId
      }
      updateComponentInfo({
        components: [this.form],
        isCompileConfigToAll: isCompileConfigToAll,
        operateType: this.operateType
      }).then(res => {
        this.$message.success('更新成功')
        this.$emit('edit-submit')
      }).catch(err => {
        console.error(err)
        this.$message.error('更新失败')
      })
    },

    onCancel() {
      this.$emit('edit-cancel', false)
    },

    // 下线组件
    offlineComp() {
      onOfflineComps({
        compIds: [this.componentInfo.id],
        activeType: 0
      }).then(res => {
        this.$message.success('操作成功')
        // 触发刷新表格数据
        this.$emit('flush-comps')
      }).catch(err => {
        console.error(err)
        this.$message.error('操作失败')
      })
    },

    // 设置组件环境弹窗
    setCompEnv() {
      this.envVisible = true
      this.compBanEnvHosts = this.form.envHosts
    },

    fetchConfigsByKey() {
      this.complierVers = []
      const configKey = this.form.compType === $const.COMP_TYPE_FRONTEND ? 'NODE_JS' : 'JAVA_HOME'
      getConfigsByKey({ configKey: configKey }).then(res => {
        res.data.forEach(item => {
          this.complierVers.push({
            label: item.alias,
            value: item.configValue
          })
        })
      }).catch(err => {
        console.error(err)
      })
    },

    // 提交组件环境设置
    compEnvCancel(val) {
      this.envVisible = val
    },
    compEnvSubmit(selectEnvRows) {
      this.$set(this.form, 'envHosts', selectEnvRows.map(item => item.host))
      this.$set(this.form, 'envIds', selectEnvRows.map(item => item.id))
      this.envVisible = false
    },
    fetchTagList() {
      if (this.branchTagList.length > 1) {
        return
      }
      this.$emit('fetch-tags', this.componentInfo)
    },

    changeCompType(val) {
      this.fetchConfigsByKey()
    }
  }
}
</script>

<style>
.tags-container {
  position: relative; /* 关键定位容器 */
  min-height: 40px; /* 最小高度保证无标签时按钮位置 */
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.tags-wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 8px; /* 标签间距 */
  align-items: center;
  max-height: 100px; /* 最大高度限制 */
  overflow-y: auto; /* 超出滚动 */
  border: 0;
}

.add-btn {
  position: absolute;
  top: -26px;
  right: -10px;
  padding: 8px !important; /* 调整按钮大小 */
}

</style>
